import { request } from '../../request/index'
Page({
  data: {
    tabs: [
      {
        id: 0,
        value: '全部',
        isActive: false
      },
      {
        id: 1,
        value: '待付款',
        isActive: false
      },
      {
        id: 2,
        value: '待发货',
        isActive: false
      },
      {
        id: 3,
        value: '退款/退货',
        isActive: false
      }
    ],
    ordersList: []
  },
  onShow () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index'
      })
      return
    } 
    let { type } =  getCurrentPages().splice(-1)[0].options
    this.activeIndex(type - 1)
    this.getOrdersList(type)
  },
  handelTabsItemChange(e) {
    const { index } = e.detail
    this.activeIndex(index)
    this.getOrdersList(index + 1)
  },
  activeIndex(index) {
    let { tabs } = this.data
    tabs.forEach((v, i) => {
      v.isActive = i === index ? true : false
    })
    this.setData({
      tabs
    })
  },
  async getOrdersList(type) {
    const { data: res } = await request({
      url: '/my/orders/all',
      data: {
        type
      }
    })
    if (res.meta.status !== 200) return

    this.setData({
      ordersList: res.message.orders.map(item => ({
        ...item,
        create_time_cn: new Date(item.create_time*1000).toLocaleDateString()
      }))
    })
  }
})